//
//  CHAddressController.m
//  CarFile
//
//  Created by 陈浩 on 2017/12/14.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHAddressController.h"
#import "CHAddressCell.h"
#import <CoreLocation/CoreLocation.h>
#import "SectionGroupModel.h"
#import "ProvinceModel.h"
@interface CHAddressController ()<UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate>
{
    

    CGFloat cellWith;
    NSString *cityName;
    UITableView *tableView;
    NSMutableArray *_citys;

    
}
@property (nonatomic, strong) CLLocationManager* locationManager;    //  定位服务

@end

@implementation CHAddressController
// 注意const的位置
static NSString *const cellId = @"cellId";
static NSString *const headerId = @"headerId";
static NSString *const footerId = @"footerId";

-(NSMutableArray *)citys{
    
    if (!_citys) {
        _citys = [NSMutableArray array];
    }
    return _citys;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"地区选择";
    
//    [self locationStart];
    
    UIButton *btn  = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.size = CGSizeMake(40, 40);
    [btn setTitle:@"取消" forState: UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(dismissView) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"f3f3f3" alpha:1.0f];
   
    
    
    [self setupTableView];
}


-(void)dismissView{
    
      [self dismissViewControllerAnimated:YES completion:NULL];
}

-(void)setupTableView{
    
    tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, UIScreenH -64) style:UITableViewStylePlain];
    tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = [UIColor colorWithHexString:@"f3f3f3" alpha:1.0f];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.sectionHeaderHeight = 25;
    [self.view addSubview:tableView];
    
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.sectionArr.count +2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section >1) {
        
        CHAddressCell *cell = [CHAddressCell cellForTableView:tableView];
        cell.backgroundColor = [UIColor colorWithHexString:@"f3f3f3" alpha:1.0f];

        SectionGroupModel *model = self.sectionArr[indexPath.section -2];
        cell.titles = model.provinces;
        cell.sectionTitle = model.firstLetter;
       
        __weak typeof(self) weakSelf = self;
        cell.block = ^(ProvinceModel *model) {
            
            [Util setObject:model.name key:@"cityname"];
            
            if (weakSelf.block) {
                weakSelf.block(model);
            }
            [self dismissViewControllerAnimated:YES completion:NULL];
        };
        return cell;
    }
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    cell.backgroundColor = [UIColor whiteColor];
    cell.textLabel.font = Font(14);
    if (indexPath.section == 0) {
        
   
            cell.textLabel.text = (NSString *)[Util getValue:@"cityname"];
        
        
    }else if (indexPath.section == 1){
        
        cell.textLabel.textColor = [UIColor colorWithHexString:@"098edd" alpha:1.0f];
        cell.textLabel.text = (NSString *)[Util getValue:@"cityname"];
    }
    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section > 1) {
       
        SectionGroupModel *group = self.sectionArr[indexPath.section - 2];
        return [CHAddressCell getCellHeightOfCityArray:group.provinces];
    }
    return 40;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 0, UIScreenW-20, 25)];
    UILabel *label = [[UILabel alloc] initWithFrame:view.bounds];
    label.textColor = [UIColor lightGrayColor];
    label.font = Font(12);
    [view addSubview:label];
    if (section == 0) {
        label.text = @"     当前默认选择的省份";
    }else if (section == 1){
        label.text = @"     最近访问的省";
    }else if (section == 2 ){
        label.text = @"     按省级区域划分";
    }
    return view;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{

    NSMutableArray *titles = [NSMutableArray array];
    for (int i = 0; i < self.sectionArr.count; i++) {
        SectionGroupModel *group = self.sectionArr[i];
        [titles addObject:group.firstLetter];
    }
    return [NSArray arrayWithArray:titles];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 50;
    if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}


//开始定位
-(void)locationStart{
    //判断定位操作是否被允许
    
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init] ;
        self.locationManager.delegate = self;
        //设置定位精度
        self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters;//每隔多少米定位一次（这里的设置为每隔百米)
        if (IOS8) {
            //使用应用程序期间允许访问位置数据
            [self.locationManager requestWhenInUseAuthorization];
        }
        // 开始定位
        [self.locationManager startUpdatingLocation];
    }else {
        //提示用户无法进行定位操作
        NSLog(@"%@",@"定位服务当前可能尚未打开，请设置打开！");
        
    }
}
#pragma mark - CoreLocation Delegate

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [self.locationManager stopUpdatingLocation];
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    
    //获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count >0)
         {
             CLPlacemark *placemark = [array objectAtIndex:0];
             //获取城市
             NSString *currCity = placemark.administrativeArea;
//             if (!currCity) {
//                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
//                 currCity = placemark.administrativeArea;
//             }
             cityName = currCity;
             [tableView reloadData];
             
             //             if (self.localCityData.count <= 0) {
             //                 GYZCity *city = [[GYZCity alloc] init];
             //                 city.cityName = currCity;
             //                 city.shortName = currCity;
             //                 [self.localCityData addObject:city];
             //
             //                 [self.tableView reloadData];
             //             }
             
         } else if (error ==nil && [array count] == 0)
         {
             NSLog(@"No results were returned.");
         }else if (error !=nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
         
     }];
    
}


- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    if (error.code ==kCLErrorDenied) {
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
    }
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
